<template>
  <div class="devices-container">
    <div class="toolbar">
      <el-form :inline="true" :model="searchForm">
        <el-form-item label="设备名称">
          <el-input v-model="searchForm.name" placeholder="可输入设备名称"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="resetSearch">刷新</el-button>
          <el-button type="success" @click="openAddDialog">添加设备</el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-table :data="deviceList" border style="width: 100%">
      <el-table-column prop="name" label="设备名称" width="180"></el-table-column>
      <el-table-column prop="description" label="描述"></el-table-column>
      <el-table-column label="操作" width="180">
        <template #default="scope">
          <el-button
            type="primary"
            size="small"
            @click="openEditDialog(scope.row)"
          >
            编辑
          </el-button>
          <el-button
            type="danger"
            size="small"
            @click="deleteDevice(scope.row)"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 添加设备对话框 -->
    <el-dialog
      v-model="addDialogVisible"
      title="添加媒体设备"
      width="30%"
      :before-close="handleCloseAddDialog"
    >
      <el-form :model="addForm" ref="addFormRef" label-width="80px">
        <el-form-item label="设备名称" prop="name" :rules="[{ required: true, message: '请输入设备名称', trigger: 'blur' }]">
          <el-input v-model="addForm.name"></el-input>
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input type="textarea" v-model="addForm.description"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handleCloseAddDialog">取消</el-button>
          <el-button type="primary" @click="submitAddDevice">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 编辑设备对话框 -->
    <el-dialog
      v-model="editDialogVisible"
      title="编辑媒体设备"
      width="30%"
      :before-close="handleCloseEditDialog"
    >
      <el-form :model="editForm" ref="editFormRef" label-width="80px">
        <el-form-item label="设备名称" prop="name" :rules="[{ required: true, message: '请输入设备名称', trigger: 'blur' }]">
          <el-input v-model="editForm.name"></el-input>
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input type="textarea" v-model="editForm.description"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handleCloseEditDialog">取消</el-button>
          <el-button type="primary" @click="submitEditDevice">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <div class="pagination">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[5, 10, 20, 30, 50]"
        :total="total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      >
      </el-pagination>
    </div> 
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import request from '../../api/request' 

const deviceList = ref([])
const addDialogVisible = ref(false)
const addFormRef = ref(null)
const addForm = ref({
  name: '',
  description: ''
})

const searchForm = ref({
  name: '',
  pageNum: 1,
  pageSize: 10
})

const editDialogVisible = ref(false)
const editFormRef = ref(null)
const editForm = ref({
  id: null,
  name: '',
  description: ''
})

// 分页相关
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 获取设备列表
const getDeviceList = async () => {
  try {
    const response = await request.post('/admin/media-device-list', {
      pageNum: currentPage.value,
      pageSize: pageSize.value,
      name: searchForm.value.name
    })
    if (response.code === 200) {
      deviceList.value = response.data.records
      total.value = response.data.total
    } else {
      ElMessage.error(response.message || '获取设备列表失败')
    }
  } catch (error) {
    ElMessage.error(error.message||'获取设备列表失败')
  }
}

// 处理每页数量变化
const handleSizeChange = (val) => {
  pageSize.value = val;
  currentPage.value = 1; // 页大小改变时，回到第一页
  searchForm.value.pageNum = currentPage.value;
  searchForm.value.pageSize = pageSize.value;
  getDeviceList();
}

// 处理搜索
const handleSearch = () => {
  currentPage.value = 1;
  searchForm.value.pageNum = currentPage.value;
  getDeviceList();
}

// 重置搜索
const resetSearch = () => {
  searchForm.value.name = '';
  handleSearch();
}

// 处理当前页变化
const handleCurrentChange = (val) => {
  currentPage.value = val;
  getDeviceList();
}

// 打开添加对话框
const openAddDialog = () => {
  addDialogVisible.value = true
}

// 关闭添加对话框
const handleCloseAddDialog = () => {
  addFormRef.value?.resetFields()
  addDialogVisible.value = false
}

// 打开编辑对话框
const openEditDialog = (device) => {
  editForm.value = { ...device }
  editDialogVisible.value = true
}

// 关闭编辑对话框
const handleCloseEditDialog = () => {
  editFormRef.value?.resetFields()
  editDialogVisible.value = false
}

// 提交添加设备
const submitAddDevice = async () => {
  if (!addFormRef.value) return
  if (!addFormRef.value) return
  addFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        const response = await request({
          url: '/admin/add-media-device',
          method: 'post',
          data: addForm.value
        })
        if (response.success) {
          ElMessage.success('添加成功')
          handleCloseAddDialog()
          getDeviceList()
        } else {
          ElMessage.error(response.message ||response.data|| '添加失败')
        }
      } catch (error) {
        ElMessage.error(error.message || '添加失败')
      }
    }
  })
}

// 提交编辑设备
const submitEditDevice = async () => {
  if (!editFormRef.value) return
  editFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        const response = await request({
          url: '/admin/modify-media-device',
          method: 'post', 
          data: editForm.value
        })
        if (response.success) {
          ElMessage.success('修改成功')
          handleCloseEditDialog()
          getDeviceList()
        } else {
          ElMessage.error(response.message || '修改失败')
        }
      } catch (error) {
        ElMessage.error(error.message||'修改设备失败，请检查网络或联系管理员')
      }
    }
  })
}

// 删除设备
const deleteDevice = (device) => {
  ElMessageBox.confirm(
    `确定要删除设备 "${device.name}" 吗?`,
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(async () => {
      try {
        const response = await request({
          url: `/admin/delete-media-device`,
          method: 'delete',
          data: {
            id: device.id,
          }
        })
        // 假设后端返回的数据结构包含 code 和 message
        if (response.code === 200) { // 假设成功的 code 是 200
          ElMessage.success('删除成功')
          getDeviceList() // 刷新列表
        } else {
          ElMessage.error(response.message || '删除失败')
        }
      } catch (error) {
        ElMessage.error(error.message||'删除设备失败，请检查网络或联系管理员')
      }
    })
    .catch(() => {
      // 用户取消操作
      ElMessage.info('已取消删除')
    })
}

onMounted(() => {
  getDeviceList()
})
</script>

<style scoped>
.devices-container {
  padding: 20px;
}

.toolbar {
  margin-bottom: 20px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
</style>